package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.*;
import com.sky.entity.Employee;
import com.sky.exception.PasswordEditFailedException;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.utils.ThreadLocalUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
public class EmployeeController {


    private final EmployeeService employeeService;
    private final JwtProperties jwtProperties;

    private final RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    public EmployeeController(EmployeeService employeeService, JwtProperties jwtProperties, RedisTemplate<Object, Object> redisTemplate) {
        this.employeeService = employeeService;
        this.jwtProperties = jwtProperties;
        this.redisTemplate = redisTemplate;
    }


    /**
     * 登录
     *
     * @param employeeLoginDTO 登录数据实体
     * @return 返回提示信息
     */
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        redisTemplate.opsForValue().set(token, token, 12, TimeUnit.HOURS);
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder().id(employee.getId()).userName(employee.getUsername()).name(employee.getName()).token(token).build();


        return Result.success(employeeLoginVO, MessageConstant.LOGIN_OK);
    }


    /**
     * 新增员工
     *
     * @param employeeDTO 员工信息
     * @return 提示
     */
    @PostMapping
    @ApiOperation("新增员工")
    public Result<String> save(@RequestBody EmployeeDTO employeeDTO) {
        log.info(employeeDTO.toString());
        employeeService.save(employeeDTO);
        return Result.success(MessageConstant.ADD_OK);
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO 查询实体
     * @return 所有用户列表实体
     */

    @GetMapping("/page")
    @ApiOperation("获取所有员工列表")
    public Result<PageResult<Employee>> getAll(EmployeePageQueryDTO employeePageQueryDTO) {
        log.info("员工分页查询,参数为:{}", employeePageQueryDTO);
        return Result.success(employeeService.getAll(employeePageQueryDTO), MessageConstant.SELECT_OK);
    }


    @PostMapping("/status/{status}")
    @ApiOperation("启用禁用员工账号")
    public Result<String> startOrStop(@PathVariable Integer status, Long id) {
        log.info("启用禁用员工账号:{},{}", status, id);
        employeeService.startOrStop(status, id);
        return Result.success(MessageConstant.UPDATE_OK);
    }


    /**
     * 根据id查询员工信息
     *
     * @param id 员工id
     * @return 员工数据实体
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询员工详细信息")
    public Result<Employee> findByIdGetEmployee(@PathVariable Long id) {
        return Result.success(employeeService.findByIdGetEmployee(id), MessageConstant.SELECT_OK);
    }

    /**
     * -
     * 修改员工信息
     *
     * @param employeeDTO 修改员工信息实体
     * @return 提示
     */
    @PutMapping
    @ApiOperation("修改员工信息")
    public Result<String> update(@RequestBody EmployeeDTO employeeDTO) {
        log.info("编辑员工信息为:{}", employeeDTO);
        employeeService.update(employeeDTO);
        return Result.success(MessageConstant.UPDATE_OK);
    }

    /**
     * 退出
     *
     * @return 提示信息
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    @PutMapping("/editPassword")
    @ApiOperation("员工修改密码")
    public Result<String> editPassword(@RequestBody EmployeeEditPassWordDTO passWordDTO, @RequestHeader("token") String token) {
        Employee employee = employeeService.findByIdGetEmployee(ThreadLocalUtil.get());
        if (employee.getPassword().equals(DigestUtils.md5DigestAsHex(passWordDTO.getOldPassword().trim().getBytes()))) {
            passWordDTO.setEmpId(ThreadLocalUtil.get());
            employeeService.updatePassWord(passWordDTO);
            redisTemplate.delete(token);
        } else {
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        return Result.success(MessageConstant.OPERATE_OK);
    }

}
